<?php
/***********************************************************
    [Youzie] (C)2011 - 2011 youzie.com
    This is NOT a freeware, use is subject to license terms

    @Filename XloginAction.class.php $

    @Author Rochael $

    @Date  2011-4-12 ����01:09:22 $
*************************************************************/
/**
	 * 
	 * 腾讯微博API参数
	 * @var unknown_type  
	 */
	//define("QQ_MB_AKEY","41be5b4abddd45f48f8242482c125a50"); //这里的'*********'请改成你的App Key
	//define("QQ_MB_SKEY","58cc276457f6ef451fd7f41cac1ac02f"); //这里的'*********'请改成你的App Secret
	define("QQ_MB_AKEY","d8e2a5fe55f9487b99939523fd0b3f8d"); //这里的'*********'请改成你的App Key
	define("QQ_MB_SKEY","0f228c1ba5244fd04d1200d40d62fea5"); //这里的'*********'请改成你的App Secret	
	define( "MB_RETURN_FORMAT" , 'json' );
	define( "MB_API_HOST" , 'open.t.qq.com' );

	/**
	 * 
	 * 新浪微博API参数
	 * @var unknown_type
	 */
	//define("SINA_WB_AKEY", "508859946");
	//define("SINA_WB_SKEY", "a68b0d0bb1028661cc8c39d6c061cb8d");
	define("SINA_WB_AKEY", "572936687");
	define("SINA_WB_SKEY", "1bdc19cb11f055d323f8760e6a4b2838");

class XloginAction extends Action{
	
	public function _initialize() {
        parent::init();
    }
    
	/**
	 * 
	 * 登录界面
	 * @Return return_type
	 */
	public function index(){
		
		$this->assign("regmode", "login");
		$this->display();
	}
	
	/**
	 * 用户注册界面
	 * Enter description here ...
	 * @Return return_type
	 */
	public function register(){
		$this->assign("regmode", "reg");
		
		$this->display("index");
	}
	
	
	
	/**
	 * 验证码action
	 * Enter description here ...
	 */
	public function verify(){ 
	
		import("ORG.Util.Image"); 
		
		Image::buildImageVerify(5,5,'png', null, 30, 'verifycode'); 
	
	} 
	
	
	public function resetPwd(){
		$this->assign("regmode", "reset");
		
		$this->display("index");
		$this->display();
	}
	
	
	public function registerok() {
		//$this->assign("jumpUrl","Index"); 
     	//$this->success(" 新增成功！ " );
		Session::set(sys_msg, "激活链接已发送到您的信箱,如需重新发送请点<a href=\"".SITE_URL."/Login/joinMailed?UName=".Session::get('username')."\">这里</a>!!");		
		$this->redirect("Index/");
	}
	
	public function logout() {
		Session::set('loginStatus', '');
		Session::set('userinfo', '');
		$this->redirect("Index/");
	}
	
	/**
	 * 
	 * 重发激活邮件
	 * @Author Rochael
	 * @Date 2011-4-13
	 *
	 * @access 
	 * @Return return_type
	 */
	public function joinMailed() {
		$uname = $_GET['UName'];
		
		
		//TODO 添加重新发送激活邮件发送
		
		Session::set(sys_msg, "激活链接已成功发送到您的注册信箱!!");		
		$this->redirect("Index/");
	}
	
	
	public function qqCallback() {
		require_once APP_PATH.'/Lib/OAuth/QQ/opent.php';
		$o = new MBOpenTOAuth( QQ_MB_AKEY , QQ_MB_SKEY , $_SESSION['qq_oauth_keys']['oauth_token'] , $_SESSION['qq_oauth_keys']['oauth_token_secret']);
		$last_key = $o->getAccessToken( $_REQUEST['oauth_verifier'] ) ;//获取ACCESSTOKEN
		$_SESSION['qq_last_key'] = $last_key;
		Session::set('mbtype', 'qq');
		Session::set('apiType', 2);
		$this->redirect('Xlogin/bindRegister');
			
	}
	
	public function bindRegister() {
				
		if(Session::get('mbtype') =='qq'){
		
			require_once APP_PATH.'/Lib/OAuth/QQ/api_client.php';
			$c = new MBApiClient( QQ_MB_AKEY , QQ_MB_SKEY , $_SESSION['qq_last_key']['oauth_token'] , $_SESSION['qq_last_key']['oauth_token_secret']  );
			try {
				$userinfo = $c->getUserInfo();
				if($userinfo){
					$l = $this->checkWeiBoUserID($userinfo['data']['name'], 2);
					if($l){
						Session::set('username', $l[0]['qqweibo']);
						Session::set('userinfo', $l[0]);
						Session::set('loginStatus', 'OK');
						Session::set('sys_msg', $l[0]['username'].'，您的微博绑定成功！！');
						Cookie::set('authcookie', authcode("$l[user_name]\t$l[user_id]",'ENCODE'));
						$this->redirect('Index/');
					}
					
					$this->assign('baseinfo', $userinfo);
					
				}
			} catch (Exception $e) {
				//$this->error('获取用户信息失败！');
			}
		}elseif (Session::get('mbtype')=='sina'){
			require_once APP_PATH.'/Lib/OAuth/Sina/weibooauth.php';
			$c = new WeiboClient( SINA_WB_AKEY , SINA_WB_SKEY , $_SESSION['sina_last_key']['oauth_token'] , $_SESSION['sina_last_key']['oauth_token_secret']  );
			//$ms  = $c->home_timeline(); // done
			$userinfo = $c->verify_credentials();
			if($userinfo){					
				$l = $this->checkWeiBoUserID($userinfo['id'], 1);
				if($l){
					Session::set('username', $l[0]['sinaweibo']);
					Session::set('userinfo', $l[0]);
					Session::set('loginStatus', 'OK');
					Session::set('sys_msg', $l[0]['username'].'，您的微博绑定成功！！');
					Cookie::set('authcookie', authcode("$l[user_name]\t$l[user_id]",'ENCODE'));
						
					$this->redirect('Index/');
				}
				$this->assign('baseinfo', $userinfo);
				
			}
			
		}
		
		$this->display("Index/bindRegister");
	}
	
	public function sinaCallback() {
		require_once APP_PATH.'/Lib/OAuth/Sina/weibooauth.php';
		$o = new WeiboOAuth( SINA_WB_AKEY , SINA_WB_SKEY , $_SESSION['sina_oauth_keys']['oauth_token'] , $_SESSION['sina_oauth_keys']['oauth_token_secret']  );
		$last_key = $o->getAccessToken(  $_REQUEST['oauth_verifier'] ) ;
		$_SESSION['sina_last_key'] = $last_key;
		Session::set('mbtype', 'sina');
		Session::set('apiType', 1);
		$this->redirect('Xlogin/bindRegister');
	}
	
	
	/**
	 * 
	 * 绑定本站已注册账号
	 * @Author Rochael
	 * @Date 2011-4-12
	 *
	 * @access 
	 * @Return return_type
	 */
	public function doAPIbind() {
		$user = M('Users');
		$list = $user->where("password = '".md5($_POST['BindPwd'])."' and username = '".$_POST['BindUName']."' ")->select();
		if($list){
			if($list[0]['apiUserID'] == ''){
				$data['nickname'] = $_POST['SinaUserName'];
				$data['apiUserID'] = $_POST['SinaUserID'];
				$data['apiType'] = $_POST['APIType'];
				$data['head'] = $_POST['SinaUserImgUrl'];
				$user->where("username = '".$_POST['BindUName']."'")->save($data);
				Session::set('loginStatus', 'OK');
				Session::set('userinfo', $user->where("username = '".$_POST['BindUName']."'")->find());
				Session::set('sys_msg', '登录成功！！');
			}else{
				Session::set('sys_err', '此用户已绑定了其它微博！！');
				
			}
		}else {
			Session::set('sys_err', '用户名或密码错误！！');
		}
		
		
				
		$this->redirect('Index/');
	}
	
	
	
	
	public function ajaxCheckMailExits(){
		$email = $_POST['UEmail'];
		$user = M("Users");
		$l = $user->where("email = '$email'")->select();
		if($l){
			$this->ajaxReturn($l, '用户已经存在！', 0);
		}else{
			$this->ajaxReturn($l, '邮箱可用', 1);
		}
		
	}
	
	/**
	 * 
	 * 检测邮箱是否已经存在
	 * @Author Rochael
	 * @Date 2011-4-12
	 * @Return return_type
	 */
	public function ajaxCheckUNameExits(){
		$uname = $_POST['UName'];
		$user  = M("Users");
		$l = $user->where("username = '$uname'")->select();
		if($l){
			$this->ajaxReturn($l, '用户已经存在！', 0);
		}else{
			$this->ajaxReturn($l, '用户可用', 1);
		}
	}
	
	/**
	 * 
	 * 用户注册信息, 中间没有增加验证功能
	 * 此处省略N行代码
	 * @Return return_type
	 */
	public function ajaxRegister() {
		$email = $_POST['UEmail'];
		$uname = $_POST['UName'];
		$pwd = $_POST['UPwd'];
		$checkNumber = $_POST['CheckNumber'];
		
		$n = Session::get("verifycode");
		if($n != md5($checkNumber)){
			$this->ajaxReturn(0, "验证码不正确", 3);
			return;
		}
		
		$user  = M("Users");
		$data['email'] = $email;
		$data['username'] = $uname;
		$data['password'] = md5($pwd);
		
		$id = $user->add($data);
		if($id > 0){
			Session::set('username', $uname);
			Session::set('loginStatus', "OK");
			
			
			//TODO 添加激活邮件发送
			
			
			
			$this->ajaxReturn(0, "注册成功！", 1);			
		}else{
			$this->ajaxReturn(0, "注册失败！", 0);
		}
	}
	
	public function ajaxSinaAPIJoin() {
		$user = M('Users');
		//$n = $user->where("username='".$_POST['UName']."'")->find();
		$data['username'] = $_POST['UName'];
		$data['password'] = md5($_POST['UPwd']);
		$data['nickname'] = $_POST['SinaUserName'];
		$data['apiType'] = $_POST['APIType'];
		$data['apiUserID'] = $_POST['SinaUserID'];
		$data['email'] = $_POST['UEmail'];
		$data['head'] = $_POST['SinaUserImgUrl'];
		$data['self_comment'] = $_POST['SinaUserImgUrl'];
		$id = $user->add($data);
		if($id > 0){
			$u = $user->where("userID = ". $id)->find();
			Session::set('loginStatus', 'OK');
			Session::set('userinfo', $u);
			
			//TODO 添加激活邮件发送
			$this->ajaxReturn($id, '注册账号成功！', 1);
		}else {
			$this->ajaxReturn(0, '注册账号失败！', 0);
		}
		
	}
	
	public function ajaxLogin() {
		$uname = $_POST['UName'];
		$pwd = $_POST['UPwd'];
		$nextlog = $_POST['nextlog'];
		
		$user  = M("Users");
		$u = $user->where("(username = '".$uname."' or email = '".$uname."') and password = '".md5($pwd)."'")->find();
		if($u){
			
			Session::set('username', $uname);
			Session::set('loginStatus', 'OK');
			Session::set('userinfo', $u);
			$this->ajaxReturn(0, "登录成功！", 1);
		}else{
			$this->ajaxReturn(0, "登录失败！", 0);
		}
	}
	
	
	
	
	
	
	
	
	public function goQQAPI() {
		require_once APP_PATH.'/Lib/OAuth/QQ/opent.php';
		$o = new MBOpenTOAuth( QQ_MB_AKEY , QQ_MB_SKEY  );
		$keys = $o->getRequestToken(SITE_URL.'/Xlogin/qqCallback');//这里填上你的回调URL
		$aurl = $o->getAuthorizeURL( $keys['oauth_token'] ,false,'');
		$_SESSION['qq_oauth_keys'] = $keys;
		header('location: '.$aurl);
	}
	
	public function goSinaAPI() {
		require_once APP_PATH.'/Lib/OAuth/Sina/weibooauth.php';
		$o = new WeiboOAuth( SINA_WB_AKEY , SINA_WB_SKEY  );
		$keys = $o->getRequestToken();
		$aurl = $o->getAuthorizeURL( $keys['oauth_token'] ,false , SITE_URL.'/Xlogin/sinaCallback');
		
		$_SESSION['sina_oauth_keys'] = $keys;
		header('location: '.$aurl);
	}
	
	/**
	 * 
	 * 检测API登录的用户是否在网站已绑定
	 * @param mix $userid
	 * @param int $apiType
	 * @Return Model
	 */
	private function checkWeiBoUserID($userid, $apiType) {
		$user = M('Users');
		if($apiType == 1)
		$l = $user->where("sinaweibo = '{$userid}'")->select();
		else 
		$l = $user->where("qqweibo = '{$userid}'")->select();
		return $l;
	}
	
	//------------------ 我今天增加的内容，测试Google SVN
	
}
